package chagine.mdt.feign;

import chagine.core.ErrorCode;
import chagine.core.restful.util.TResponse;
import chagine.core.util.Assert;
import chagine.mdt.config.properties.ParamsMsgPushProperties;
import chagine.mdt.feign.vo.msgpush.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class MsgPushUtil {

    @Resource
    private MsgPushClient msgPushClient;
    @Resource
    private ParamsMsgPushProperties paramsMsgPushProperties;
    @Resource
    private ObjectMapper objectMapper;

    /**
     * 发送消息请求
     */
    public <T extends MsgPushApiBaseSendVo> String sendMessage(T sendVo, String errorMessage) {
        MsgPushResQueryMessageStatusVo statusVo = createRequestAndGet(sendVo, MsgPushResQueryMessageStatusVo.class, errorMessage);
        return statusVo.getMessageId();
    }

    /**
     * 查询发送的消息状态
     */
    public MsgPushResQueryMessageStatusVo queryMsgStatus(String messageId) {
        MsgPushApiQueryMsgStatusVo sendVo = new MsgPushApiQueryMsgStatusVo();
        sendVo.setMessageId(messageId);
        return createRequestAndGet(sendVo, MsgPushResQueryMessageStatusVo.class, "消息状态查询失败");
    }

    /**
     * 查询生成短链接
     */
    public MsgPushResConversionLinkVo conversionLink(MsgPushApiConversionLinkVo sendVo) {
        return createRequestAndGet(sendVo, MsgPushResConversionLinkVo.class, "长短链接查询状态异常");
    }

    private <T extends MsgPushReqBaseVo, V> V createRequestAndGet(T data, Class<V> clazz, String errorMessage) {
        MsgPushApiRequest<T> apiRequest = generateJsonRequestData(data);
        TResponse<Object> tResponse = msgPushClient.pushMessage(apiRequest);
        Assert.error(!tResponse.isSuccess(), ErrorCode.BUSINESS_EXCEPTION, errorMessage + ":" + tResponse.getMessage());
        Object responseData = tResponse.getData();
        return objectMapper.convertValue(responseData, clazz);
    }

    /**
     * 构建请求对象
     *
     * @param data 请求对象
     */
    private <T extends MsgPushReqBaseVo> MsgPushApiRequest<T> generateJsonRequestData(T data) {
        MsgPushApiRequest<T> request = new MsgPushApiRequest<>();
        request.setData(data);
        MsgPushApiCommonData commonData = new MsgPushApiCommonData(paramsMsgPushProperties.getAccessKey(), System.currentTimeMillis(), data.getAction(), data.getVersion());
        request.setCommon(commonData);
        // 由于进行服务间请求，不需要进行签名
        return request;
    }

}
